<template>
  <view class="container p-bottom">
    <!-- 配送地址 -->
    <view @tap.stop.prevent="selectAddress">
      <view v-if="exist_address && address.address_default && address.address_default.address_id">
        <view class="b-f">
          <view class="flow-checkout-header">
            <text class="iconfont icon-dingwei"></text>
            <view class="flow-header-left">
              <view class="flow-checkout-admin f-30 col-3">
                <text>{{ address.address_default.name }}</text>
                <text>{{ address.address_default.phone }}</text>
                <text class="col-m"></text>
              </view>
              <view class="flow-checkout-address f-28">
                {{ address.address_default.region.province }} {{ address.address_default.region.city }}
                {{ address.address_default.region.region }}
                {{ address.address_default.detail }}
              </view>
            </view>
            <view class="flow-header-right pr-12">
              <text class="iconfont icon-xiangyoujiantou user-orderJtou"></text>
            </view>
          </view>
        </view>
      </view>
      <view v-else>
        <view class="flow-checkout-header">
          <text class="iconfont icon-dingwei"></text>
          <view class="flow-header-left">
            <view class="f-28 col-6">去选择配送地址</view>
          </view>
          <view class="flow-header-right p-r15">
            <text class="iconfont icon-xiangyoujiantou user-orderJtou"></text>
          </view>
        </view>
      </view>

    </view>

    <!-- 商品列表 -->
    <view class="m-top20">
      <view class="checkout_list" v-for="(item, index) in goods_list" :key="index">
        <navigator :url="'../goods/index?item_id=' + item.goods_id">
          <view class="dis-flex flow-shopList" :data-index="index">
            <view class="flow-list-left">
              <image mode="scaleToFill" :src="item.image[0].file_path"></image>
            </view>
            <view class="flow-list-right">
              <text class="f-30 col-3 twolist-hidden">{{ item.goods_name }}</text>
              <text
                  class="f-26 col-7">{{ item.goods_sku ? item.goods_sku.goods_attr : item.goods_remark }}
              </text>
              <view class="flow-list-cont">
                <text class="flow-cont">￥{{ item.goods_price }}</text>
                <text class="small">×{{ item.total_num }}</text>
                <view class="zhekou" v-if="item.level != null && item.vip > 0">
                  会员折扣：{{ item.agio }}折,折后价{{ (item.goods_price * item.agio) / 10 }}
                </view>
              </view>
            </view>
          </view>
        </navigator>
      </view>
      <view class="flow-num-box b-f padding-box">
        <text>共{{ order_total_num }}件商品，合计：</text>
        <text class="flow-money col-m">￥{{ order_total_price }}</text>
      </view>
    </view>

    <view class="flow-all-money b-f m-top20">
      <view class="ipt-wrapper dis-flex flow-all-list">
        <input @input="bindRemark" placeholder="选填：买家留言（50字以内）" :value="remark"/>
      </view>
    </view>

    <!-- 商品金额 -->
    <view class="flow-all-money b-f m-top20">
      <view class="dis-flex flow-all-list">
        <text class="flex-five">商品总金额:</text>
        <view class="flex-five t-r">
          <text class="col-m">￥{{ order_total_price }}</text>
        </view>
      </view>
      <view class="dis-flex flow-all-list">
        <text class="flex-five">优惠券：</text>
        <view class="flex-five t-r">
          <view class="" @tap.stop.prevent="togglePopupCoupon()">
            <view v-if="coupon_list.length > 0">
              <text class="col-m" v-if="selectCoupon.couponId">-￥{{ selectCoupon.reduced_price }}</text>
              <text class="col-m" v-else>有{{ coupon_list.length }}张优惠券可用</text>
              <text class="iconfont icon-xiangyoujiantou user-orderJtou"></text>
            </view>
            <text v-else class="">无优惠券可用</text>
          </view>
        </view>
      </view>
      <view v-if="address && address.level  && agio_count > 0" class="dis-flex flow-all-list">
        <text class="flex-five">会员省：</text>
        <view class="flex-five t-r">
          <text class="col-m">￥{{ agio_count }}</text>
        </view>
      </view>
      <view class="dis-flex flow-all-list">
        <text class="flex-five">配送费用：</text>
        <view class="flex-five t-r">
          <view v-if="address && address.address_id">
            <text class="col-m" v-if="intra_region">+￥{{ express_price }}</text>
            <text v-else>不在配送范围</text>
          </view>
          <view v-else>
            <text class="col-7">请先选择配送地址</text>
          </view>
        </view>
      </view>

      <view class="payment-methods">
        <radio-group @change="onPaymentMethodChange">
          <label v-for="method in paymentMethods" :key="method.value" class="radio-item">
            <span class="label-text">{{ method.name }}</span>
            <radio :checked="method.value === pay_way" :value="method.value" class="custom-radio"/>
          </label>
        </radio-group>
      </view>
      <view v-if="qrCodeUrl && pay_way==='transfer'" class="qr-code-container">
        <image @tap="previewImages" :src="qrCodeUrl" class="qr-code" mode="widthFix"/>
        <text class="qr-code-label">请使用微信扫码支付</text>
        <text class="qr-code-label">支付完成记得提交</text>
      </view>
    </view>

    <!-- <view class="f-34" style='height: 100px; background: #000;color: #fff; line-height: 100px; text-align: center;' catchtap="togglePopupCoupon">从底部弹出popup</view> -->

    <!-- 提交订单 -->
    <view class="flow-fixed-footer b-f m-top10">
      <view class="dis-flex chackout-box">
        <view class="chackout-left pl-12">
          实付款：
          <text class="col-m">￥{{ actual_pay_price > 0 ? actual_pay_price : order_pay_price }}</text>
        </view>
        <view @tap="submitOrder" class="chackout-right">
          <text class="flow-btn f-32" :data-prom="prom">提交订单</text>
        </view>
      </view>
    </view>

    <!-- 快捷导航 -->
    <view :class="'filter-menu ' + (nav_select ? 'active' : '')">
      <view class="filter-menu-list ts-5">
        <custom-ul>
          <custom-li @tap.native="nav($event, { index: 'home' })" data-index="home">
            <text class="iconfont icon-home"></text>
          </custom-li>
          <custom-li @tap.native="nav($event, { index: 'fenlei' })" data-index="fenlei">
            <text class="iconfont icon-fenlei"></text>
          </custom-li>
          <custom-li @tap.native="nav($event, { index: 'cart' })" data-index="cart">
            <text class="iconfont icon-cart"></text>
          </custom-li>
          <custom-li @tap.native="nav($event, { index: 'profile' })" data-index="profile">
            <text class="iconfont icon-profile"></text>
          </custom-li>
          <custom-li class="w"></custom-li>
        </custom-ul>
      </view>
      <view @tap="commonNav" class="filter-menu-title"></view>
    </view>

    <!-- 优惠券弹出框 -->
    <zan-popup :show="showBottomPopup" type="bottom" @close="togglePopupCoupon">
      <view class="popup__coupon">
        <view class="coupon__title f-32">选择优惠券</view>
        <!-- 不使用优惠券 -->
        <view class="coupon__do_not dis-flex flex-y-center flex-x-center">
          <view class="control dis-flex flex-y-center flex-x-center" @tap.stop.prevent="doNotCouponTap">
            <text class="f-26">不使用优惠券</text>
          </view>
        </view>
        <!-- 优惠券列表 -->
        <view class="coupon-list">
          <scroll-view :scroll-y="true" style="height: 565rpx">
            <view class="coupon-item" v-for="(item, index) in coupon_list" :key="index">
              <view :class="'item-wrapper color__' + item.color.text" @tap.stop.prevent="selectCouponTap"
                    :data-index="index" :data-coupon-id="item.user_coupon_id">
                <view class="coupon-type">{{ item.coupon_type.text }}</view>
                <view class="tip dis-flex flex-dir-column flex-x-center">
                  <view v-if="item.coupon_type.value == 10">
                    <text class="f-30">￥</text>
                    <text class="money">{{ item.reduce_price }}</text>
                  </view>
                  <text class="money" v-if="item.coupon_type.value == 20">{{ item.discount }}折</text>
                  <text class="pay-line">满{{ item.min_price }}元可用</text>
                </view>
                <view class="split-line"></view>
                <view class="content dis-flex flex-dir-column flex-x-between">
                  <view class="title">{{ item.name }}</view>
                  <view class="bottom dis-flex flex-y-center">
                    <view class="time flex-box">
                      <text>有效期：{{ item.start_time.text }}~{{ item.end_time.text }}</text>
                    </view>
                    <!-- <view class="state flex-box">
                    <text>-￥{{ item.reduced_price }}</text>
                  </view> -->
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="footer-fixed f-32">
          <view @tap="togglePopupCoupon" class="order-bt" style="width: 100%">关闭</view>
        </view>
      </view>
    </zan-popup>
  </view>
</template>

<script>
import zanPopup from '@/pages/popup/index';

let app = getApp();
export default {
  components: {
    zanPopup
  },
  data() {
    return {
      // 快捷导航
      nav_select: false,
      qrCodeUrl: '', // 用于存储二维码的URL
      pay_way: 'wechat',
      paymentMethods: [
        { value: 'wechat', name: '微信支付' },
        //{ value: 'alipay', name: '支付宝' },
        { value: 'transfer', name: '转账支付' },
       // { value: 'pay_for_me', name: '代付' }
      ],
      // 当前页面参数
      options: {},

      address: null,

      // 默认收货地址
      exist_address: false,

      // 是否存在收货地址
      goods: {},

      // 商品信息

      // 选择的优惠券
      selectCoupon: {
        index: null,
        couponId: null,
        reduced_price: '0.00'
      },

      // 买家留言
      remark: '',

      // 禁用submit按钮
      disabled: false,

      hasError: false,
      error: '',
      showBottomPopup: false,
      actual_pay_price: '',
      address_id: '',
      name: '',
      phone: '',

      region: {
        province: '',
        city: '',
        region: ''
      },

      detail: '',
      goods_list: [],
      order_total_num: 0,
      order_total_price: '',
      coupon_list: [],
      agio_count: 0,
      intra_region: '',
      express_price: '',
      order_pay_price: '',
      prom: ''
    };
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 当前页面参数
    this.options = options;
    //console.log(options)
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取当前订单信息
    this.getOrderData();
  },
  methods: {
    onPaymentMethodChange(e) {
      this.pay_way = e.detail.value;
    },
    fetchQRCodeUrl() {
      // 这里应该是调用API获取二维码URL的逻辑
      // 示例：直接设置一个静态URL
      //this.qrCodeUrl = 'http://xcx996.test.top/uploads/qrcode/wx.png';
    },
    /**
     * 获取当前订单信息
     */
    getOrderData: function () {
      let that = this;
      let options = that.options; // 获取订单信息回调方法
      let callback = function (result) {
        if (result.code !== 1) {
          app.globalData.showError(result.msg);
          return false;
        }

        // 显示错误信息
        if (result.data.has_error) {
          that.hasError = true;
          that.error = result.data.error_msg;
          app.globalData.showError(that.error);
        }
        that.setData(result.data);
      };

      // 立即购买
      if (options.order_type === 'buyNow') {
        //console.log(options.item_id+'_1');
        app.globalData._get(
            'order/buyNow', {
              item_id: options.item_id,
              goods_num: options.goods_num,
              prom: options.prom,
              other: options.other,
              item_sku_id: options.item_sku_id == '1' ? options.item_id + '_1' : options.item_sku_id
            },
            function (result) {
              console.log(result);
              callback(result);
            }
        );
      }

      // 购物车结算
      else if (options.order_type === 'cart') {
        app.globalData._get(
            'order/cart', {
              cart_ids: options.cart_ids
            },
            function (result) {
              callback(result);
            }
        );
      }
    },

    /**
     * 选择收货地址
     */
    selectAddress: function () {
      uni.navigateTo({
        url: '../address/' + (this.exist_address ? 'index?from=flow' : 'create')
      });
    },

    /**
     * 订单提交
     */
    submitOrder: function () {
      let that = this;
      let options = that.options;
      if (that.disabled) {
        return false;
      }
      if (that.hasError) {
        app.globalData.showError(that.error);
        return false;
      }

      // 订单创建成功后回调--微信支付
      let callback = function (result) {
        if (result.code === -10) {
          app.globalData.showError(result.msg, function () {
            // 跳转到未付款订单
            uni.redirectTo({
              url: '../order/index'
            });
          });
          return false;
        }
        if (that.pay_way==="wechat"){
          // 发起微信支付
          uni.requestPayment({
            timeStamp: result.data.payment.timeStamp,
            nonceStr: result.data.payment.nonceStr,
            package: 'prepay_id=' + result.data.payment.prepay_id,
            signType: 'MD5',
            paySign: result.data.payment.paySign,
            success: function (res) {
              // 跳转到订单详情
              uni.redirectTo({
                url: '../order/detail?order_id=' + result.data.order_id
              });
            },
            fail: function () {
              app.globalData.showError('订单未支付', function () {
                // 跳转到未付款订单
                uni.redirectTo({
                  url: '../order/index'
                });
              });
            }
          });
        }else if(that.pay_way==="transfer"){
            app.globalData.showSuccess('订单已提交，请等待管理员审核', function () {
              uni.redirectTo({
                url: '../order/detail?order_id=' + result.data.order_id
              });
            },2000,'none')
        }

      };

      // 按钮禁用, 防止二次提交
      that.disabled = true;

      // 显示loading
      uni.showLoading({
        title: '正在处理...'
      });

      // 创建订单-立即购买
      if (options.order_type === 'buyNow') {
        app.globalData._post_form(
            'order/buyNow', {
              item_id: options.item_id,
              goods_num: options.goods_num,
              item_sku_id: options.item_sku_id == '1' ? options.item_id + '_1' : options.item_sku_id,
              prom: options.prom,
              other: options.other,
              coupon_id: that.selectCoupon.couponId,
              remark: that.remark,
              pay_way: that.pay_way
            },
            function (result) {
              // success
              callback(result);
            },
            function (result) {
              // fail
            },
            function () {
              // complete

              uni.hideLoading();
              // 解除按钮禁用
              that.disabled = false;
            }
        );
      }

      // 创建订单-购物车结算
      else if (options.order_type === 'cart') {
        app.globalData._post_form(
            'order/cart', {
              cart_ids: options.cart_ids,
              coupon_id: that.selectCoupon.couponId,
              remark: that.remark
            },
            function (result) {
              // success
              console.log('success');
              callback(result);
            },
            function (result) {
              // fail
              console.log('fail');
            },
            function () {
              // complete
              console.log('complete');
              uni.hideLoading();
              // 解除按钮禁用
              that.disabled = false;
            }
        );
      }
    },

    /**
     * 买家留言
     */
    bindRemark: function (e) {
      this.setData({
        remark: e.detail.value
      });
    },

    /**
     * 快捷导航 显示/隐藏
     */
    commonNav: function () {
      this.setData({
        nav_select: !this.nav_select
      });
    },

    /**
     * 快捷导航跳转
     */
    nav: function (e, _dataset) {
      /* ---处理dataset begin--- */
      this.handleDataset(e, _dataset);
      /* ---处理dataset end--- */
      let url = '';
      switch (e.currentTarget.dataset.index) {
        case 'home':
          url = '../index/index';
          break;
        case 'fenlei':
          url = '../category/index';
          break;
        case 'cart':
          url = '../flow/index';
          break;
        case 'profile':
          url = '../user/index';
          break;
      }
      uni.switchTab({
        url
      });
    },

    /**
     * 选择优惠券(弹出/隐藏)
     */
    togglePopupCoupon() {
      if (this.coupon_list.length > 0) {
        this.setData({
          showBottomPopup: !this.showBottomPopup
        });
      }
    },

    /**
     * 浏览商品图片
     */
    previewImages: function (e) {
      let index = e.currentTarget.dataset.index;
      let imageUrls = [];
      imageUrls.push(this.qrCodeUrl);
      uni.previewImage({
        current: imageUrls[index],
        urls: imageUrls
      });
    },

    /**
     * 选择优惠券
     */
    selectCouponTap: function (e) {
      let dataset = e.currentTarget.dataset;
      // 优惠券折扣金额
      let reducedPrice = this.coupon_list[dataset.index].reduced_price;
      dataset.reduced_price = reducedPrice;
      // 计算优惠后的价格
      let actualPayPrice = this.bcsub(this.order_pay_price, reducedPrice);
      this.setData({
        selectCoupon: dataset,
        actual_pay_price: actualPayPrice > 0 ? actualPayPrice : '0.01'
      });
      this.togglePopupCoupon();
    },

    /**
     * 不使用优惠券
     */
    doNotCouponTap: function () {
      this.setData({
        selectCoupon: {},
        actual_pay_price: this.order_pay_price
      });
      this.togglePopupCoupon();
    },

    /**
     * 数学运算相减
     */
    bcsub: function (arg1, arg2) {
      return (Number(arg1) - Number(arg2)).toFixed(2);
    }
  }
};
</script>
<style>
@import './checkout.css';
</style>